//
//  SongDetailViewController.m
//  Music
//
//  Created by mac on 16/4/23.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "SongDetailViewController.h"
#import "SongModel.h"
#import "songPlayLyModel.h"
#import "ActivitySrcollView.h"


@interface SongDetailViewController ()<UITableViewDataSource,UITableViewDelegate,STKAudioPlayerDelegate>

@property (nonatomic , strong)  NSMutableArray *splModelArr;
@property (nonatomic , strong)  NSNumber *songId;
@property (nonatomic , strong)  NSString *lyric;
@property (nonatomic , strong)  NSMutableArray *lyricStrArr;
@property (nonatomic , strong)  NSMutableArray *lyricTimeArr;
@property (nonatomic , strong)  UITableView *tableView;
@property (nonatomic , strong)  NSTimer *timer;
@property (nonatomic , strong)  NSString *currTime;
@property (nonatomic , strong)  NSMutableArray *lyricArr;
@property (nonatomic , strong)  NSMutableDictionary *lrcDictionary;
@property (nonatomic , strong)  ActivitySrcollView *circleView;
@property (nonatomic , strong)  NSMutableArray *imgArr;
@property (nonatomic , strong)  UIVisualEffectView *effectView;
@property (nonatomic , strong)  UIScrollView *backScrollView;
@property (nonatomic , strong)  UITableView *smallTableView;
@property (nonatomic , strong)  UIView *bottomView;
@property (nonatomic , strong)  UILabel *currTimeLabel;
@property (nonatomic , strong)  UILabel *totalTimeLabel;
@property (nonatomic , strong)  UISlider *playSlide;
@property (nonatomic , strong)  UIButton *circleBtn;
@property (nonatomic , strong)  UIButton *frontBtn;
@property (nonatomic , strong)  UIButton *playBtn;
@property (nonatomic , strong)  UIButton *nextBtn;
@property (nonatomic , strong)  UIButton *downLoadBtn;
@property (nonatomic , strong)  UILabel *songName;
@property (nonatomic , strong)  UILabel *singer;
@property (nonatomic , strong)  UIButton *storeBtn;
@property (nonatomic , strong) UIImageView *backImageView;
@property (nonatomic , strong)  NSString *url;
@property (nonatomic , strong)  UIButton *shareBtn;
@end

@implementation SongDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    

    self.player = [Player shareInstance];
    self.player.player.delegate = self;
    self.songArr = self.player.songArr;

    self.num = self.player.num;
    [self createTimer];
    
    
    self.backImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"background"]];
    
    self.backImageView.frame = self.view.bounds;
    
    [self.view addSubview:_backImageView];
    
    [self createCircleView];
    
    [self createEffectView];

    [self createBackScrollView];
    
    [self createBottomView];
    
    [self createHeaderViews];
    
    [self createTableView];
    
    [self createSmallTableView];
    
    [self dataHandle];

    self.lyricStrArr = [NSMutableArray array];
    self.lyricTimeArr = [NSMutableArray array];
    self.lrcDictionary = [NSMutableDictionary dictionary];
    
    
}

- (void)createTableView{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(kWIDTH, 150, kWIDTH, kHEIGHT - 150 - self.bottomView.frame.size.height) style:(UITableViewStylePlain)];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.userInteractionEnabled = NO;
    self.tableView.rowHeight = 60;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor clearColor];
    [self.backScrollView addSubview:_tableView];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"tCell"];
}

- (void)createSmallTableView{
    self.smallTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kHEIGHT - self.bottomView.frame.size.height - 100, kWIDTH, 120) style:(UITableViewStylePlain)];
    self.smallTableView.dataSource = self;
    self.smallTableView.delegate = self;
    self.smallTableView.userInteractionEnabled = NO;
    self.smallTableView.rowHeight = 60;
    self.smallTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.smallTableView.backgroundColor = [UIColor clearColor];
    [self.backScrollView addSubview:_smallTableView];
    [self.smallTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"stCell"];

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.lyricTimeArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.tableView) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tCell" forIndexPath:indexPath];
        
        cell.textLabel.text = self.lrcDictionary[self.lyricTimeArr[indexPath.row]];
        cell.backgroundColor = [UIColor clearColor];
        cell.textLabel.textAlignment = NSTextAlignmentCenter;
        cell.textLabel.numberOfLines = 0;
        cell.textLabel.shadowOffset = CGSizeMake(1, 1);
        cell.textLabel.shadowColor = [UIColor blackColor];
        cell.textLabel.font = [UIFont systemFontOfSize:20];
        cell.textLabel.textColor = [UIColor whiteColor];
        cell.textLabel.alpha = 0.5;
        
        cell.selectionStyle  = UITableViewCellSelectionStyleNone;
        
        // 设置文字高亮颜色
        //        cell.textLabel.highlightedTextColor = [UIColor colorWithRed:0.2 green:0.3 blue:0.9 alpha:1];
        
        return cell;
    } else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"stCell" forIndexPath:indexPath];
        
        cell.textLabel.text = self.lrcDictionary[self.lyricTimeArr[indexPath.row]];
        cell.backgroundColor = [UIColor clearColor];
        cell.textLabel.textAlignment = NSTextAlignmentCenter;
        cell.textLabel.font = [UIFont systemFontOfSize:20.0];
        cell.textLabel.numberOfLines = 0;
        cell.textLabel.textColor = [UIColor whiteColor];
        cell.textLabel.alpha = 0.5;
        cell.textLabel.shadowColor = [UIColor blackColor];
        cell.textLabel.shadowOffset = CGSizeMake(1, 1);
        cell.textLabel.backgroundColor = [UIColor clearColor];
        cell.selectionStyle  = UITableViewCellSelectionStyleNone;
        
        return cell;
    }
}

- (void)createBottomView{
    
    CGFloat space = (kWIDTH - 300 - 20) / 4.0;
    
    UIColor *bColor = [UIColor whiteColor];
    
    self.bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, kHEIGHT - 170, kWIDTH, 170)];
    //    self.bottomView.backgroundColor = [UIColor colorWithWhite:0.2 alpha:0.8];
    [self.bottomView.layer addSublayer:[self shadowAsInverse]];
    [self.view addSubview:_bottomView];
    
    self.currTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 60, 60)];
    self.currTimeLabel.backgroundColor = [UIColor clearColor];
    self.currTimeLabel.font = [UIFont systemFontOfSize:17];
    self.currTimeLabel.textColor = [UIColor whiteColor];
    self.currTimeLabel.textAlignment = NSTextAlignmentCenter;
    [self.bottomView addSubview:self.currTimeLabel];

    
    self.totalTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(kWIDTH - 10 - 60, 0, 60, 60)];
    self.totalTimeLabel.backgroundColor = [UIColor clearColor];
    self.totalTimeLabel.font = [UIFont systemFontOfSize:17];
    self.totalTimeLabel.textColor = [UIColor whiteColor];
    self.totalTimeLabel.textAlignment = NSTextAlignmentCenter;
    [self.bottomView addSubview:self.totalTimeLabel];
    
    self.playSlide = [[UISlider alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.currTimeLabel.frame) + 10, 0, kWIDTH - (60 + 20) * 2, 60)];
    self.playSlide.maximumValue = self.player.player.duration;
    self.playSlide.thumbTintColor = [UIColor whiteColor];
    self.playSlide.minimumTrackTintColor = [UIColor whiteColor];
    self.playSlide.maximumTrackTintColor =  [UIColor colorWithWhite:1 alpha:0.5];
    [self.bottomView addSubview:self.playSlide];
    [self.playSlide addTarget:self action:@selector(changeProgress:) forControlEvents:(UIControlEventValueChanged)];
    
    self.circleBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.circleBtn.frame = CGRectMake(10, 60 + 10, 40, 90);
    self.circleBtn.backgroundColor = [UIColor clearColor];
    self.circleBtn.tintColor = bColor;
    [self setCircleBtnImg:self.circleType];
    [self.circleBtn addTarget:self action:@selector(changeCircleMode:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.bottomView addSubview:self.circleBtn];
    
    self.frontBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.frontBtn.frame = CGRectMake(_circleBtn.frame.size.width + _circleBtn.frame.origin.x + space, _circleBtn.frame.origin.y, 70, 90);
    self.frontBtn.backgroundColor = [UIColor clearColor];
    self.frontBtn.tintColor = [UIColor whiteColor];
    [self.frontBtn setImage:[[UIImage imageNamed:@"front"] imageWithRenderingMode:(UIImageRenderingModeAlwaysTemplate)] forState:(UIControlStateNormal)];
    [self.frontBtn addTarget:self action:@selector(frontSong:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.bottomView addSubview:self.frontBtn];
    
    self.playBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.playBtn.frame = CGRectMake(_frontBtn.frame.origin.x + _frontBtn.frame.size.width + space, _circleBtn.frame.origin.y, 80, 90);
    self.playBtn.backgroundColor = [UIColor clearColor];
    self.playBtn.tintColor = [UIColor whiteColor];
    [self.playBtn setImage:[[UIImage imageNamed:@"play"] imageWithRenderingMode:(UIImageRenderingModeAlwaysTemplate)] forState:(UIControlStateNormal)];
    [self.playBtn setImage:[[UIImage imageNamed:@"zanting"] imageWithRenderingMode:(UIImageRenderingModeAlwaysTemplate)] forState:(UIControlStateSelected)];
    if (self.player.player.state == STKAudioPlayerStatePlaying) {
        self.playBtn.selected = YES;
    }
    [self.playBtn addTarget:self action:@selector(play:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.bottomView addSubview:self.playBtn];
    
    self.nextBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.nextBtn.frame = CGRectMake(_playBtn.frame.size.width + _playBtn.frame.origin.x + space, _circleBtn.frame.origin.y, 70, 90);
    self.nextBtn.backgroundColor = [UIColor clearColor];
    self.nextBtn.tintColor = [UIColor whiteColor];
    [self.nextBtn setImage:[[UIImage imageNamed:@"next"] imageWithRenderingMode:(UIImageRenderingModeAlwaysTemplate)] forState:(UIControlStateNormal)];
    [self.nextBtn addTarget:self action:@selector(nextSong:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.bottomView addSubview:self.nextBtn];
    
    self.downLoadBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.downLoadBtn.frame = CGRectMake(_nextBtn.frame.size.width + _nextBtn.frame.origin.x + space, _circleBtn.frame.origin.y, 40, 90);
    self.downLoadBtn.backgroundColor = [UIColor clearColor];
    self.downLoadBtn.tintColor = [UIColor whiteColor];
    [self.downLoadBtn setImage:[[UIImage imageNamed:@"xiazai"] imageWithRenderingMode:(UIImageRenderingModeAlwaysTemplate)] forState:(UIControlStateNormal)];
    [self.downLoadBtn addTarget:self action:@selector(downLoad:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.bottomView addSubview:self.downLoadBtn];
    
}

- (void)frontSong:(UIButton *)btn{
    [self.player frontSong];
    
    self.num = self.player.num;
    
    [self dataHandle];
    
}

- (void)play:(UIButton *)btn{
    if (self.songArr.count) {
        if (STKAudioPlayerStatePlaying == self.player.player.state) {
            [self.player pause];
            btn.selected = NO;
            
        } else if (STKAudioPlayerStatePaused == self.player.player.state) {
            
            // 继续
            [self.player resume];
            
            btn.selected = YES;
            
        } else {
            
//            if (self.type == 1) {
//                RadioSongModel *radioSongModel = _songArr[self.num];
//                [self.player playUrl:radioSongModel.url_list[0][@"url"]];
//            }
            if (self.type == 2) {
                SongModel *songModel = _songArr[_num];
                if (songModel.urlList.count != 0) {
                    [self.player playUrl:songModel.urlList[0][@"url"]];
                }
            }
            if (self.type == 3) {
                NSDictionary *dic = self.songArr[self.num];
                NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
                NSString *path = [documentPath stringByAppendingPathComponent:[NSString stringWithFormat:@"db/%@",dic[@"path"]]];
                [self.player playFile:path];
            }
            btn.selected = YES;
        }
    }
}

- (void)nextSong:(UIButton *)btn{
    [self.player nextSong];
    
    self.num = self.player.num;
    
    [self dataHandle];
}



//- (void)downLoad:(UIButton *)btn{
//    if ([[DataBaseManager shareInstance] selectDownloadWithName:self.songName.text]) {
//        // 抖动动画 是旋转动画的变形
//        CAKeyframeAnimation *shakeAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation"];
//        // 抖动时 向上偏移的角度
//        float top = M_PI / 18;
//        // 向上偏移的角度
//        float bottom = -M_PI / 18;
//        shakeAnimation.values = @[@(top), @(0), @(bottom), @(0), @(top)];
//        shakeAnimation.repeatCount = NSIntegerMax;
//        shakeAnimation.duration = 0.3;
//        [btn.layer addAnimation:shakeAnimation forKey:@"key"];
//        
//        // 4s后移除动画 停止抖动
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            // 停止动画
//            [btn.layer removeAnimationForKey:@"key"];
//        });
//    } else{
//        NSString *picUrl = nil;
//        if (self.imgArr.count) {
//            picUrl = self.imgArr[0];
//        }
//        if (self.type == 1) {
//            RadioSongModel *radioSongModel = _songArr[self.num];
//            self.url = radioSongModel.url_list[0][@"url"];
//        }
//        if (self.type == 2) {
//            SongModel *songModel = _songArr[_num];
//            if (songModel.urlList.count != 0) {
//                self.url  = songModel.urlList[0][@"url"];
//            }
//        }
//        CAKeyframeAnimation *likeAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale"];
//        // 设置关键帧的值,values是数组类型
//        likeAnimation.values = @[@(0.1),@(1.0),@(1.5)];
//        likeAnimation.duration = 0.5;
//        [btn.layer addAnimation:likeAnimation forKey:@"key"];
//        [[DownLoadManager shareInstance] addDownLoadTaskWithName:self.songName.text singerName:self.singer.text pic:picUrl url:self.url lydic:self.lrcDictionary];
//    }
//}

- (void)changeCircleMode:(UIButton *)btn{
    self.circleType++;
    if (self.circleType > 2) {
        self.circleType = 0;
    }
    self.player.circleType = self.circleType;
    [self setCircleBtnImg:self.circleType];
}

- (void)setCircleBtnImg:(NSInteger)type{
    if (type == 0) {
        [self.circleBtn setImage:[[UIImage imageNamed:@"shunxu"] imageWithRenderingMode: (UIImageRenderingModeAlwaysTemplate)] forState:(UIControlStateNormal)];
    } else if (type == 1){
        [self.circleBtn setImage:[[UIImage imageNamed:@"xunhuan"] imageWithRenderingMode:(UIImageRenderingModeAlwaysTemplate)] forState:(UIControlStateNormal)];
    } else {
        [self.circleBtn setImage:[[UIImage imageNamed:@"suiji"] imageWithRenderingMode:(UIImageRenderingModeAlwaysTemplate)] forState:(UIControlStateNormal)];
    }
    self.player.circleType = type;
}

- (void)changeProgress:(UISlider *)slider{
    [self.player.player seekToTime:slider.value];
    [self timerTake];
}

- (void)createEffectView{
    // 毛玻璃效果
    UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    
    self.effectView = [[UIVisualEffectView alloc] initWithEffect:effect];
    
    self.effectView.frame = self.circleView.bounds;
    
    self.effectView.alpha = 0;
    
    [self.circleView addSubview:self.effectView];
    

}

//翻动 产生毛玻璃效果
- (void)createBackScrollView{
    self.backScrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    self.backScrollView.backgroundColor = [UIColor clearColor];
    self.backScrollView.delegate = self;
    self.backScrollView.contentSize = CGSizeMake(kWIDTH * 2, kHEIGHT);
    self.backScrollView.pagingEnabled = YES;
    self.backScrollView.bounces = NO;
    [self.view addSubview:_backScrollView];

}

//歌手图片 轮播图
- (void)createCircleView{
    self.circleView = [[ActivitySrcollView alloc] initWithFrame:self.view.bounds];
    self.circleView.userInteractionEnabled = NO;
    self.circleView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.circleView];

    

}

- (void)createTimer{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.3 target:self selector:@selector(timerTake) userInfo:nil repeats:YES];
    //    [self.timer fire];
}

- (void)timerTake{
    self.playSlide.value = self.player.player.progress;
    self.playSlide.maximumValue = self.player.player.duration;
    NSInteger currTime = (NSInteger)self.player.player.progress;
    self.currTimeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld",currTime / 60, (currTime % 60)];
    
    NSInteger totalTime = (NSInteger)self.player.player.duration;
    self.totalTimeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld",totalTime / 60, (totalTime % 60)];
    
    [self time];
}

- (void)time{
    if (self.lyricTimeArr != nil && self.lyricStrArr != nil) {
        for (int i = 0; i < self.lyricTimeArr.count; i++) {
            
            if ([self.lyricTimeArr[i] integerValue] == (NSInteger)self.player.player.progress) {
                
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
                
                [self.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionMiddle];
                [self.smallTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionTop];
                
                if (indexPath.row > 0){
                    [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:(indexPath.row - 1)inSection:0]].textLabel.font = [UIFont systemFontOfSize:20];
                    [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:(indexPath.row - 1)inSection:0]].textLabel.alpha = 0.5;
                    [self.smallTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:(indexPath.row - 1)inSection:0]].textLabel.font = [UIFont systemFontOfSize:20];
                    [self.smallTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:(indexPath.row - 1)inSection:0]].textLabel.alpha = 0.5;
                }
                [self.tableView cellForRowAtIndexPath:indexPath].textLabel.font = [UIFont systemFontOfSize:24];
                [self.tableView cellForRowAtIndexPath:indexPath].textLabel.alpha = 1;
                [self.smallTableView cellForRowAtIndexPath:indexPath].textLabel.font = [UIFont systemFontOfSize:24];
                [self.smallTableView cellForRowAtIndexPath:indexPath].textLabel.alpha = 1;
            }
        }
    }
}

- (void)createHeaderViews{
    UIButton *backBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    backBtn.frame = CGRectMake(10, 30, 50, 50);
    backBtn.backgroundColor = [UIColor clearColor];
    [backBtn setImage:[[UIImage imageNamed:@"back"] imageWithRenderingMode:(UIImageRenderingModeAlwaysTemplate)] forState:(UIControlStateNormal)];
    backBtn.tintColor = [UIColor  whiteColor];
    [backBtn addTarget:self action:@selector(back) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:backBtn];
    
    self.songName = [[UILabel alloc] initWithFrame:CGRectMake(backBtn.frame.origin.x + backBtn.frame.size.width + 15, backBtn.frame.origin.y +10, kWIDTH - backBtn.frame.origin.x - backBtn.frame.size.width - 30 - 70, 40)];

    self.songName.backgroundColor = [UIColor clearColor];
    self.songName.shadowColor = [UIColor blackColor];
    self.songName.shadowOffset = CGSizeMake(1, 1);
    self.songName.textColor = [UIColor whiteColor];
    self.songName.font = [UIFont systemFontOfSize:20];
    [self.view addSubview:self.songName];

    
    self.singer = [[UILabel alloc] initWithFrame:CGRectMake(self.songName.frame.origin.x , self.songName.frame.origin.y + self.songName.frame.size.height + 5, self.songName.frame.size.width, 30)];
    self.singer.backgroundColor = [UIColor clearColor];
    self.singer.shadowOffset = CGSizeMake(1, 1);
    self.singer.shadowColor = [UIColor blackColor];
    self.singer.textColor = [UIColor whiteColor];
    [self.view addSubview:self.singer];

}

- (CAGradientLayer *)shadowAsInverse
{
   CAGradientLayer *newShadow = [[CAGradientLayer alloc] init];
    CGRect newShadowFrame = CGRectMake(0, 0, kWIDTH, 220);
    newShadow.frame = newShadowFrame;
    //添加渐变的颜色组合（颜色透明度的改变）
    newShadow.colors = [NSArray arrayWithObjects:
                        (id)[[[UIColor blackColor] colorWithAlphaComponent:0.2] CGColor] ,
                        (id)[[[UIColor blackColor] colorWithAlphaComponent:0.3] CGColor],
                        (id)[[[UIColor blackColor] colorWithAlphaComponent:0.5] CGColor],
                        (id)[[[UIColor blackColor] colorWithAlphaComponent:0.7] CGColor],
                        (id)[[[UIColor blackColor] colorWithAlphaComponent:0.9] CGColor],
                        (id)[[[UIColor blackColor] colorWithAlphaComponent:1] CGColor],
                        nil];
    return newShadow ;
}

-(void)back{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)dataHandle
{
    NSString *str = nil;
    NSString *imgStr = nil;
    CGFloat scale = [UIScreen mainScreen].scale;
    CGRect rect = [UIScreen mainScreen].bounds;

    SongModel *songModel = self.songArr[self.num];
    
    NSString *title = UrlEncodedString(songModel.name);
    
    NSString *artist = UrlEncodedString(songModel.singerName)
    ;
    str = [NSString stringWithFormat:@"http://search.dongting.com/lyric/search?title=%@&song_id=%@&artist=%@&duration_ms=%@",title,songModel.songId,artist,songModel.urlList[0][@"duration"]];
    
    imgStr = [NSString stringWithFormat:@"http://search.dongting.com/artwork/search?singerid=%@&artist=%@&title=%@&x=%ld&y=%ld",songModel.singerId,artist,title,(long)(rect.size.width * scale),(long)(rect.size.height * scale)];
    
    self.songId = songModel.songId;
    self.songName.text = songModel.name;
    self.singer.text = songModel.singerName;

    self.splModelArr = [NSMutableArray array];
    
    [NetworkHandle GetDataForSonglyricWithURL:str dic:nil success:^(id responseObject) {
        
        self.splModelArr = [songPlayLyModel transformWithArray: responseObject[@"data"]];
        
        [self lyricDataHandle];
    } filed:^(NSError *error) {
        [self.tableView reloadData];
        [self.smallTableView reloadData];
    }];
    
    
    [NetworkHandle GetDataWithURL:imgStr dic:nil success:^(id responseObject) {
        self.imgArr = [NSMutableArray array];
        if ([responseObject[@"data"][0][@"picUrls"] count] <= 5) {
            for (NSDictionary *dic in responseObject[@"data"][0][@"picUrls"]) {
                [self.imgArr addObject:dic[@"picUrl"]];
            }
        } else {
            for (int i = 0; i <= 4; i++) {
                [self.imgArr addObject:responseObject[@"data"][0][@"picUrls"][i][@"picUrl"]];
            }
        }
        
        
        if (self.imgArr.count) {
            self.backImageView.hidden = YES;
            [self.circleView setImages:self.imgArr];
//            if (self.imgArr.count == 1) {
//                self.circleView
//            }

        }
        
    } filed:^(NSError *error) {
        
    }];
    
}

NSString* UrlEncodedString(NSString* sourceText)
{
    NSString *result = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)sourceText,NULL,CFSTR("!*'();:@&=+$,/?%#[]"), kCFStringEncodingUTF8));
    return result;
}


- (void)lyricDataHandle{
    NSString *title = nil;
    NSString *artist = nil;
    
    
        SongModel *songModel = self.songArr[self.num];
        
        title = UrlEncodedString(songModel.name);
        
        artist = UrlEncodedString(songModel.singerName);

    
    songPlayLyModel *currModel = nil;
    
    for (songPlayLyModel *splModel in self.splModelArr) {
        if ([splModel.trc isEqualToNumber:@(1)]) {
            currModel = splModel;
            break;
        }
    }
    
    if (currModel) {
        NSString *str = [NSString stringWithFormat:@"http://search.dongting.com/lyric/content?song_id=%@&lrcid=%@&type=%@&artist=%@&title=%@",self.songId,currModel.mId,currModel.type,artist,title];
        
        [NetworkHandle GetDataForSonglyricSecondWithURL:str dic:nil success:^(id responseObject) {
            ;
            if ([responseObject[@"data"] isKindOfClass:[NSDictionary class]] && responseObject[@"data"][@"content"]) {
                
                self.lyric = responseObject[@"data"][@"content"];
                
                [self createLyric];
                
                [_smallTableView reloadData];
                [_tableView reloadData];
            } else{
                [_smallTableView reloadData];
                [_tableView reloadData];
            }
        } filed:^(NSError *error) {;
            [_smallTableView reloadData];
            [_tableView reloadData];
        }];
    } else {
        [_smallTableView reloadData];
        [_tableView reloadData];
    }
}

- (void)createLyric{
    NSArray *array = [self.lyric componentsSeparatedByString:@"\n"];
    
    self.lyricArr = [NSMutableArray array];
    
    [self lyricArrayHandle:array];
}

- (NSString *)timeToSecond:(NSString *)str{
    NSString *minStr = [str substringWithRange:NSMakeRange(0, 2)];
    NSInteger mins = [minStr integerValue];
    NSString *secStr = [str substringWithRange:NSMakeRange(3, 2)];
    NSInteger secs = [secStr integerValue];
    NSInteger totalSec = mins * 60 + secs;
    return [NSString stringWithFormat:@"%03ld",(long)totalSec];
}

- (void)lyricArrayHandle:(NSArray *)array{
    
    for (NSString *str in array) {
        NSMutableString *newStr = [str mutableCopy];
        NSInteger i = 1;
        while (i) {
            NSRange range = [newStr rangeOfString:@"<"];
            NSRange rangeEnd = [newStr rangeOfString:@">"];
            if (range.length == 0) {
                i = 0;
            } else{
                [newStr replaceCharactersInRange:NSMakeRange(range.location, rangeEnd.location - range.location + 1) withString:@""];
            }
        }
        [self.lyricArr addObject:newStr];
    }
    
    for (int i = 0; i < [self.lyricArr count]; i++) {
        
        NSString *lineString = [self.lyricArr objectAtIndex:i];
        
        NSArray *lineArray = [lineString componentsSeparatedByString:@"]"];
        
        if ([lineArray[0] length] > 8) {
            
            NSString *str1 = [lineString substringWithRange:NSMakeRange(3, 1)];
            
            NSString *str2 = [lineString substringWithRange:NSMakeRange(6, 1)];
            
            if ([str1 isEqualToString:@":"] && [str2 isEqualToString:@"."]) {
                
                for (int i = 0; i < lineArray.count - 1; i++) {
                    
                    NSString *lrcString = [lineArray objectAtIndex:lineArray.count - 1];
                    
                    //分割区间求歌词时间
                    NSString *timeString = [self timeToSecond:[[lineArray objectAtIndex:i] substringWithRange:NSMakeRange(1, 5)]];
                    
                    //把时间 和 歌词 加入词典
                    [self.lrcDictionary setObject:lrcString forKey:timeString];
                }
            }
        }
    }
    
    self.lyricTimeArr = [self.lrcDictionary.allKeys mutableCopy];
    [self.lyricTimeArr sortUsingSelector:@selector(compare:)];
    
}


#pragma mark - player代理方法
- (void)audioPlayer:(STKAudioPlayer *)audioPlayer didFinishPlayingQueueItemId:(NSObject *)queueItemId withReason:(STKAudioPlayerStopReason)stopReason andProgress:(double)progress andDuration:(double)duration{
    if ((self.num <= (self.songArr.count - 1)) && ((stopReason == 1) || duration < progress)) {
        if (self.circleType == 0) {
            if (self.num == self.songArr.count - 1) {
                self.num = 0;
            } else{
                self.num++;
            }
        } else if (self.circleType == 1){
            
        } else {
            self.num = arc4random() % (self.songArr.count);
        }
        
        [self.player stop];
        self.player.num = self.num;
        [self.player play];
       // [self dataHandle];
    }
}

//必须实现的5个协议方法
- (void)audioPlayer:(STKAudioPlayer *)audioPlayer stateChanged:(STKAudioPlayerState)state previousState:(STKAudioPlayerState)previousState{
    
}

- (void)audioPlayer:(STKAudioPlayer *)audioPlayer didCancelQueuedItems:(NSArray *)queuedItems{
    
}

- (void)audioPlayer:(STKAudioPlayer *)audioPlayer didStartPlayingQueueItemId:(NSObject *)queueItemId{
    
}

- (void)audioPlayer:(STKAudioPlayer *)audioPlayer didFinishBufferingSourceWithQueueItemId:(NSObject *)queueItemId{
    
}

- (void)audioPlayer:(STKAudioPlayer *)audioPlayer unexpectedError:(STKAudioPlayerErrorCode)errorCode{
    
}

#pragma mark - scrollView代理方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView == self.backScrollView) {

        self.effectView.alpha = scrollView.contentOffset.x / kWIDTH;
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if (scrollView == self.backScrollView) {

        self.effectView.alpha = scrollView.contentOffset.x / kWIDTH;
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
